#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <dirent.h>
#include <sys/file.h>

int twsystem(char *command, int printFlag)
{
	int pid = 0, status = 0;

	if( !command )
	{
		printf("twsystem: Null Command, Error!");
		return -1;
	}

	pid = fork();
	if ( pid == -1 )
	{
	    printf("twsystem fork fail\n");
		return -1;
	}

	if ( pid == 0 )
	{
		char *argv[4];
		int i = 0;
		sigset_t sigset;
		int sig = 0;
		
		sigemptyset(&sigset);
		
		for (sig = 0; sig < (_NSIG-1); sig++)
		{
			sigaddset(&sigset, sig);
		}
		sigprocmask(SIG_UNBLOCK, &sigset, NULL);

		for (sig = 0; sig < (_NSIG-1); sig++)
		{
			signal(sig, SIG_DFL);
		}
		
		argv[0] = "sh";
		argv[1] = "-c";
		argv[2] = command;
		argv[3] = 0;
		if (printFlag)
		{
        #if 0
			printf("%04lus.[system]: %s\r\n", tbsGetLogicUpTime(), command);
        #else
			printf("[system]: %s\r\n", command);
        #endif
			//syslog(LOG_DEBUG, command);
		}
		execv("/bin/sh", argv);
		exit(127);
	}
#if 1
	/* wait for child process return */
	do
	{
		//if ( waitpid(pid, &status, 0) == -1 )
		if ( waitpid(pid, &status, 0) == -1 )
		{
			if ( errno != EINTR && errno != ECHILD )
			{
			    printf("twsystem waitpid fail, errno->%s\n", strerror(errno));
				return -1;
			} 
			else if( errno == ECHILD ) 
			{
			    //printf("twsystem child exit\n");
				return 0;            
			}
		}
		else
		{
			return status;
		}
	} while ( 1 );
#endif

	return status;
}

void main()
{
	//char cmd[128] = "ping -c 5 -s 1024 -W 10 192.168.0.101 > ./result_ping.txt";
	char cmd[128] = {0};

	printf("father start, run child now\n");	
	//sprintf(cmd, "%s", "ping -c 5 -s 1024 -W 10 192.168.0.101 > ./result_ping.txt");
	sprintf(cmd, "%s", "./child");
	twsystem(cmd, 1);
	printf("father twsystem returned\n");	
	printf("father end\n");	
}
